package com.android.fragmentdemo.defineviews
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.core.view.get
import com.android.fragmentdemo.databinding.PullToRefereshHeadBinding
import com.android.fragmentdemo.setVisibilityState

class PullToRefreshHead  @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context, attributeSet) {

    private val mBinding: PullToRefereshHeadBinding

    init {
        mBinding = PullToRefereshHeadBinding.inflate(LayoutInflater.from(context), this, true)
        //inflate(context, R.layout.pull_to_referesh_head, this)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var viewHeight = 0
        for (i in 0.until(childCount)) {
            val child = get(i)
            val layoutParams = child.layoutParams as MarginLayoutParams
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
            viewHeight += layoutParams.topMargin + child.measuredHeight
        }
        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec) - paddingStart - paddingEnd,
            MeasureSpec.makeMeasureSpec(
                viewHeight,
                MeasureSpec.EXACTLY
            ) - paddingTop - paddingBottom,
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        for (i in 0.until(childCount)) {
            val child = get(i)
            val layoutParams = child.layoutParams as MarginLayoutParams
            child.layout(
                layoutParams.leftMargin,
                layoutParams.topMargin,
                layoutParams.leftMargin + child.measuredWidth,
                layoutParams.topMargin + child.measuredHeight
            )
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return super.onInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        return super.onTouchEvent(event)
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

    fun setHeadTipAlpha(alpha: Float) {
        mBinding.tvHeadTip.alpha = Math.min(alpha,1.0F)
    }

    fun setHeadTipVisibility(visible: Boolean) {
        mBinding.tvHeadTip.setVisibilityState(visible)
    }

    fun setHeadProgressBarVisibility(visible: Boolean) {
        mBinding.pbHeadProgress.setVisibilityState(visible)
    }

    companion object {
        const val TAG = "PullToRefreshHead"
    }
}